package ServerStuff;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import DataStorageClasses.ReviewEntry;
import Database.DatabaseConnector;

/**
 * Servlet implementation class ReviewBusServlet
 */
@WebServlet("/ReviewBusServlet")
public class ReviewBusServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("getting the reviews");
		HttpSession session = request.getSession();
		DatabaseConnector db = new DatabaseConnector();
		int number = 20;
		//Integer.valueOf(request.getParameter("number"));
		boolean logged = (Boolean) session.getAttribute("loggedIn");
		
		System.out.println("business");
		System.out.println(number);
		if(logged){
		try {
			
			String business = (String) session.getAttribute("username");
			ArrayList<ReviewEntry> reviews = db.getReviewsByDate(number, business);
			JSONObject result = new JSONObject();
			
			JSONArray jArray = new JSONArray();
			for(ReviewEntry review : reviews) {
				JSONObject json = new JSONObject();
				json.put("poster", review.getUserID());
				System.out.println(review.getUserID());
				json.put("content", review.getContent());
				System.out.println(review.getContent());
				jArray.put(json);
			}
			
			result.put("reviews", jArray);
			response.getWriter().print(result.toString());
			response.setStatus(HttpURLConnection.HTTP_ACCEPTED);
		} 
		catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		}
		}
		else{
			System.out.println("fail bussiness loggin");
			response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
		}
	}
		

}
